import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "uploadServlet",urlPatterns = "/upload")
public class uploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       request.setCharacterEncoding("text/html;charset=utf-8");
       response.setContentType("utf-8");
       if (!ServletFileUpload.isMultipartContent(request)){
           return;
       }
       FileItemFactory factory = new DiskFileItemFactory();
       ServletFileUpload upload= new ServletFileUpload(factory);
       upload.setFileSizeMax(1024*1024*30);
       upload.setSizeMax(1024*1024*40);
       upload.setHeaderEncoding("utf-8");
       String path= getServletContext().getRealPath("./")+File.separator+"upload";
       File uploadDir = new File(path);
       if (!uploadDir.exists()){
           uploadDir.mkdirs();
       }
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            if (fileItems!=null&&fileItems.size()>0){
                for (FileItem fileItem : fileItems) {
                    String fileName = new File(fileItem.getName()).getName();
                    String filepath= path+File.separator+fileName;
                  File file=new File(filepath);
                  fileItem.write(file);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request,response);

    }
}
